package com.ruoyi.common.utils;


import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.Base64.Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Base64;
import java.util.UUID;

public class ImageUtils {


    // 判断文件是否存在
    public static boolean isFileExists(String path) {
        File file=new File(path);
        return file.exists();
    }

    /**
     * base64 编码转换为 BufferedImage
     * @param base64
     * @return
     */
    public  static BufferedImage base64ToBufferedImage(String base64) {
        Decoder decoder = Base64.getDecoder();
//        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        try {
            byte[] bytes1 = decoder.decode(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            return ImageIO.read(bais);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * base64转inputStream
     * @param base64string
     * @return
     */
    public static InputStream BaseToInputStream(String base64string){
        ByteArrayInputStream stream = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base64string);
            stream = new ByteArrayInputStream(bytes1);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return stream;
    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 判断文件夹是否存在
    public static void judeDirExists(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                System.out.println("dir exists");
            } else {
                System.out.println("the same name file exists, can not create dir");
            }
        } else {
            System.out.println("dir not exists, create it ...");
            file.mkdir();
        }
    }


    public static File base64StrToFile(String base64Str, String parentPath, String fileName) {
        judeDirExists(new File(parentPath));
        fileName = StringUtils.isNotEmpty(fileName) ? fileName : UUID.randomUUID() + ".jpg";
        File file = new File(parentPath, fileName);
        FileOutputStream out = null;
        try {
            byte[] bytes1 = new BASE64Decoder().decodeBuffer(base64Str);
            ByteArrayInputStream in = new ByteArrayInputStream(bytes1);
            byte[] buffer = new byte[1024];
            out = new FileOutputStream(file);
            int byteSum = 0;
            int byteRead = 0;
            while ((byteRead = in.read(buffer)) != -1) {
                byteSum += byteRead;
                out.write(buffer, 0, byteRead);
            }
        } catch (Exception ex) {
            throw new RuntimeException("transform base64 String into file 出错", ex);
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return file;
    }
    /**
     * 不传入文件名则自动命名
     *
     * @param imgStr
     * @param imgFilePath
     * @param filename
     * @return
     */
    public static String GenerateImagePath(String imgStr, String imgFilePath, String filename) {// 对字节数组字符串进行Base64解码并生成图片
        filename = StringUtils.isNotEmpty(filename) ? filename : UUID.randomUUID() + ".jpg";
        String path = new StringBuffer()
                .append(imgFilePath)
                .append(filename).toString();

        if (imgStr == null) // 图像数据为空
            return "";
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成图片
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return path;
        } catch (Exception e) {
            return "";
        }
    }



}
